<?php

define("USE_CURL", true);
function attribs($node)
{
	$attribs = array();
	if(!$node) {
		return false;
		//throw new Exception("Unable to get node attributes; this likely means that we were unable to retrieve data for the entered realm/guild from the Armory. Please check your input and/or try again later.");
	}

	foreach($node->attributes() as $key => $attrib) {
		$attribs[$key] = (string)$attrib;
	}
	return $attribs;
}

function getArmoryDataXML($url)
{
	do
	{
		//echo "Loading \"".$url."\"\n";
		$f = "";
		sleep(10);
		if(USE_CURL) {
 			$ch = curl_init();
			$timeout = 30; // set to zero for no timeout
			$useragent="Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.1.1) Gecko/20061204 Firefox/2.0.0.1";
			curl_setopt ($ch, CURLOPT_URL, $url);
			curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1);
			curl_setopt ($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
			curl_setopt ($ch, CURLOPT_USERAGENT, $useragent);
			$f = curl_exec($ch);
			curl_close($ch);
		} else {
			$f = file_get_contents($url);
		}
		@$xml = simplexml_load_string($f);

		if (@$xml->errorhtml)
		{
			//global $fguildlist;
			$str = "BANNED! Please wait 12 hours";
			ECHO $str;
			//fwrite($fguildlist, "\t".date("F j, Y, g:i:s a")."\n".$str."\n");
			ob_start();
			print_r($xml);
			fwrite($fguildlist, ob_get_flush());
			fclose($fguildlist);
			die();
		}
		if (!$xml)
			sleep(5);
	} while (!$xml);
	return $xml;
}

class ArmorySyncTask extends sfBaseTask
{
  protected function configure()
  {
    // // add your own arguments here
    // $this->addArguments(array(
    //   new sfCommandArgument('my_arg', sfCommandArgument::REQUIRED, 'My argument'),
    // ));

    $this->addOptions(array(
      new sfCommandOption('application', null, sfCommandOption::PARAMETER_REQUIRED, '', 'frontend'),
      new sfCommandOption('env', null, sfCommandOption::PARAMETER_REQUIRED, 'The environment', 'dev'),
      new sfCommandOption('connection', null, sfCommandOption::PARAMETER_REQUIRED, 'The connection name', 'doctrine'),
      //new sfCommandOption('file', null, sfCommandOption::PARAMETER_REQUIRED, 'LUA File to convert', 'data/RPBot.lua'),
      // add your own options here
    ));

    $this->namespace        = 'raidpoints';
    $this->name             = 'armory-sync';
    $this->briefDescription = '';
    $this->detailedDescription = <<<EOF
The [armory-sync|INFO] task does things.
Call it with:

  [php symfony armory-sync|INFO]
EOF;
  }
  
  public function doLogSection($section, $message, $size = NULL, $style ='INFO')
  {
      global $totalCount;

      $q = Doctrine::getTable("DataSyncStatus")
          ->createQuery()
          ->orderBy("date desc")
          ->limit(1);
      $r = $q->execute();

      $is = new DataSyncStatus();
      $is->setDate(gmdate("Y-m-d H:i:s", time()));
      $is->setStatus($section);
      $is->setText($message);
      //$is->setStatustotal($totalCount);
      if (isset($size))
      {
          $is->setStatusbar($size);
          $is->setStatustotal($style);
          $style = 'INFO';
          $size = null;
      }
      $is->save();
      $this->logsection($section, $message, $size, $style);
  }

  protected function execute($arguments = array(), $options = array())
  {
    // initialize the database connection
    $databaseManager = new sfDatabaseManager($this->configuration);
    $connection = $databaseManager->getDatabase($options['connection'] ? $options['connection'] : null)->getConnection();
    // add your code here
    //

    //$log = fopen("logs/sync-".date("F.d.y H-i-s", $logTime).".txt",'w');
    
	$this->doLogSection("Working", "\t".date("F d, Y, g:i:s a", time()), 0, 0);
	$this->doLogSection("Working", " ------ Phase  1 ------", 0, 0);
	$this->doLogSection("Working", " --- Loading Armory ---", 0, 0);

    global $level70;
    $level70 = array();
    
	$xml = getArmoryDataXML("http://www.wowarmory.com/guild-info.xml?r=".rawurlencode(sfConfig::get("app_server"))."&n=".rawurlencode(sfConfig::get("app_guild"))."&rhtml=n");
    //$f = file_get_contents("data/guild-info.xml");
    //$xml = simplexml_load_string($f);
    $characters = $xml->xpath("/page/guildInfo/guild/members/character");
    foreach ($characters as $char)
	{
		$data = attribs($char);

		if (@$data["level"] == sfConfig::get("app_max_level"))
		{
            //print_r($data);
			$this->doLogSection("Working", "-- Load Player: ".(utf8_decode($data["name"])));
			$level70[strtolower(utf8_decode($data["name"]))] = $data;
			$level70[strtolower(utf8_decode($data["name"]))]["noarmory"] = false;
		}
    }

//    $query = Doctrine::getTable("SafeList")
//        ->createQuery('s')
//        ->innerJoin('s.Player p')
//        ->orderBy("s.playerid");
//    $result = $query->execute();
//
//    if ($result->count() > 0)
//    {
//        $this->doLogSection("Working", " --- Safelist  Load ---");
//        $this->doLogSection("Working", " ---  (w/o armory)  ---");
//
//        foreach ($result as $safeList)
//        {
//            $name = utf8_decode($safeList->getPlayer()->getName());
//            if ($safeList->getGuildedflag() == 1)
//            {
//                $level70[strtolower(($name))] = $safeList->getPlayer()->toArray();
//                $level70[strtolower(($name))]["noarmory"] = true;
//                $this->doLogSection("Working", " -- SafeLoad: ".utf8_decode($safeList->getPlayer()->getFullname()));
//            }
//            else
//            {
//                unset($level70[(utf8_decode($name))]);
//                $this->doLogSection("Working", " -- SafeDelete: ".utf8_decode($safeList->getPlayer()->getFullname()));
//            }
//        }
//    }

    $this->doLogSection("Working", " --- Fetch  Players ---", 3, 100);

    $query = Doctrine::getTable("Player")
        ->getPlayerList()
        ->where("guildedflag=?", 1);
    $result = $query->execute();

    $playerlist = array();
    foreach ($result as $player)
    {
        $playerlist[strtolower(utf8_decode($player["name"]))] = $player->toArray();
    }

    function cb_filter($var)
    {
        global $level70;
        return ((@$level70[strtolower(utf8_decode($var["name"]))])?0:1);
    }

    $removeplayers = array_filter($playerlist, "cb_filter");
    
    if (count($removeplayers) > 0)
    {
        $this->doLogSection("Working", " --- Player Removal ---", 6, 100);
    }

    //print_r($level70);
    //print_r($playerlist);

    foreach ($removeplayers as $remove)
    {
        $query = Doctrine::getTable("Player")
            ->createQuery()
            ->where("id=?", $remove["id"]);
        $result = $query->execute();
        if ($result->count() > 0 && !$result->getFirst()->getSafeflag())
        {
            $result->getFirst()->delete();
            $this->doLogSection("Working", " -- Remove: ".($remove["name"]), 6, 100);
        }
    }

    if (count($level70) > 0)
    {
        $this->doLogSection("Working", " --- Player  Update ---", 8, 100);
    }
    $tree = array(
        0 => "treeOne",
        1 => "treeTwo",
        2 => "treeThree",
    );

    foreach ($level70 as $key => $data)
    {
        $query = Doctrine::getTable("Player")
            ->createQuery()
            ->where("name=?", $key);
        $result = $query->execute();

        $player = null;
        if ($data != null && $result->count() > 0)
        {
            $player = $result->getFirst();
        }
        else
        {
            $player = new Player();
            $player->setFullname(utf8_encode($data["name"]));
            $player->setName(utf8_encode(strtolower($data["name"])));
            $player->setAltid(1);
        }

        $player->setGuildedflag(1);
        echo "classid: ".(@$data["classId"]?@$data["classId"]:-1)." ".(@$data["classid"]?@$data["classId"]:-1)."\n";
        echo "rankid: ".(@isset($data["rank"])?@$data["rank"]:-1)." ".(@$data["rankid"]?@$data["rankid"]:-1)."\n";
        echo "genderid: ".(@isset($data["genderId"])?@$data["genderId"]:-1)." ".(@isset($data["genderid"])?@$data["genderid"]:-1)."\n";
        $player->setClassid(@($data["classId"] ? $data["classId"] : $data["classid"]));
        $player->setRaceid(@($data["raceId"] ? $data["raceId"] : $data["raceid"]));
        $player->setRankid(@($data["rank"] ? $data["rank"] : $data["rankid"]));
        $player->setGenderid(@($data["genderId"] ? $data["genderId"] : $data["genderid"]));
        $player->save();
        $this->doLogSection("Working", " -- Player: ".utf8_decode($data["name"])." ID: ".$player["id"]." ClassID: ".$player["classid"], 9, 100);


    }

    $this->doLogSection("Working", " ------ Phase  2 ------", 10, 100);
	$this->doLogSection("Working", " --- Talent Capture ---", 10, 100);

    $playerCount = count($level70);
    $count = 0;
    foreach ($level70 as $key => $data)
    {
        $d = new DataSync();
        $d->setProcess("player");
        $d->setValue(serialize(array("key"=>$key,"data"=>$data)));
        $d->save();
    }
    $bg = new BackgroundIt();
    $bg->run(sfConfig::get('sf_root_dir').'/symfony raidpoints:armory-run', sfConfig::get("app_path_to_php"));
//
//    while ($result->count() > 0)
//    {
//        $bg->sys(sfConfig::get('sf_root_dir')."/symfony raidpoints:importReason", sfConfig::get("app_path_to_php"));
//
//        if ($startTime+100 < time())
//        {
//            $this->doLogSection("Working", sfConfig::get('sf_root_dir')."/symfony raidpoints:importRun' - ".sfConfig::get("app_path_to_php"));
//            exit();
//        }
//
//        $result = $query->execute();
//    }

//    $this->doLogSection("Working", " ------ Phase 3 ------", 100, 100);
//    $this->doLogSection("Working", " --- Points Update ---", 100, 100);
//    Doctrine::getTable("PlayerHistory")->updatePoints();
//    $this->doLogSection("Finished", "Finished data armory-sync!", 100, 100);
//    sleep(2);
//    $is = new DataSyncStatus();
//    $is->setDate(gmdate("Y-m-d H:i:s", time()));
//    $is->setStatus("Ready");
//    $is->setText("Ready for next import.");
//    $is->setStatustotal(0);
//    $is->setStatusbar(0);
//    $is->save();


    /*
    $r = Doctrine::getTable("History")->getLastLog('2009-07-05 17:01:59', 10, 1);
    $r = $r->getFirst();

    $r = Doctrine::getTable("PlayerHistory")->updatePoints(2, 1);

    $newHistory = new History();
    $newHistory->setDate('2009-07-05 17:01:59');
    $newHistory->setActiondate('2009-07-05 17:02:51');
    $newHistory->setSavedate($newHistory->getActiondate());
    $newHistory->setLogdate(time());
    $newHistory->setLogcomment(' ');
    $newHistory->setComment(' ');
    $newHistory->setItemid(0);
    $newHistory->setOfficerid(0);
    $newHistory->setPlayerid(10);
    $newHistory->setRaidid(1);
    $newHistory->setReasonid(831);
    $newHistory->setTtype('I');
    $newHistory->setValue('0');
    $newHistory->setWaitlistflag(0);
    $newHistory->setZoneid(0);
    $newHistory->setAaction("D");
    $newHistory->save();

    $this->logsection($log, "do-nothing", "I did nothing...");
    //print_r($r->getAction());
    */


  }
}
